#!/usr/bin/perl

use strict;

open(my $fh, '<', "HillstromData.csv") or die $!;
open(my $output, '>', "ParsedData2.csv") or die $!;

my $line = <$fh>;

while(!eof($fh))
{
    $line = <$fh>;
    $line =~ /(\d+),"*(\d).*?,(\d+\.*\d*),(\d),(\d),(\w+),(\d),(\w+),([A-Za-z \-]+),(\d),(\d),(\d+\.*\d*)/;  
    
    my $rec = $1;
    my $hist_seg = $2;
    my $hist = $3;
    my $mens = $4;
    my $womens = $5;
    my $zip = $6;
    my $newb = $7;
    my $chan = $8;
    my $seg = $9;
    my $visit = $10;
    my $conv = $11;
    my $spend = $12;

    $rec = 1 << ($rec-1);
    $rec = sprintf("%b,%b,%b,%b,%b,%b,%b,%b,%b,%b,%b,%b",($rec & 1)>>0,($rec & 2)>>1,($rec & 4)>>2,
			($rec & 8)>>3, ($rec & 16)>>4, ($rec & 32)>>5, ($rec & 64)>>6, ($rec & 128)>>7,
			($rec & 256)>>8, ($rec & 512)>>9, ($rec & 1024)>>10, ($rec & 2048)>>11);
    $hist_seg = 1 << ($hist_seg-1);
    $hist_seg = sprintf("%b,%b,%b,%b,%b,%b,%b",($hist_seg & 1)>>0,($hist_seg & 2)>>1,($hist_seg & 4)>>2,
			($hist_seg & 8)>>3, ($hist_seg & 16)>>4, ($hist_seg & 32)>>5, ($hist_seg & 64)>>6);

    # if($hist_seg == 1)
    # {
    #     $hist_seg = "0,0,1";
    # }
    # elsif($hist_seg == 2)
    # {
    #     $hist_seg = "0,1,0";
    # }
    # elsif($hist_seg == 3)
    # {
    #     $hist_seg = "0,1,1";
    # }
    # elsif($hist_seg == 4)
    # {
    #     $hist_seg = "1,0,0";
    # }
    # elsif($hist_seg == 5)
    # {
    #     $hist_seg = "1,0,1";
    # }
    # elsif($hist_seg == 6)
    # {
    #     $hist_seg = "1,1,0";
    # }
    # elsif($hist_seg == 7)
    # {
    #     $hist_seg = "1,1,1";
    # }

    if($zip =~ /Rural/)
    {
        $zip = 1;
    }
    elsif($zip =~ /Surburban/)
    {
        $zip = 2;
    }
    elsif($zip =~ /Urban/)
    {
        $zip = 3;
    }
    $zip = 1 << ($zip-1);
    $zip = sprintf("%b,%b,%b",($zip & 1)>>0,($zip & 2)>>1,($zip & 4)>>2);
	
    if($chan =~ /Phone/)
    {
        $chan = 1;
    }
    elsif($chan =~ /Web/)
    {
        $chan = 2;
    }
    elsif($chan =~ /Multichannel/)
    {
        $chan = 3;
    }
    $chan = 1 << ($chan-1);
    $chan = sprintf("%b,%b,%b",($chan & 1)>>0,($chan & 2)>>1,($chan & 4)>>2);
	
    if($seg =~ /No E-Mail/)
    {
        $seg = 3;
    }
    elsif($seg =~ /Mens E-Mail/)
    {
        $seg = 2;
    }
    elsif($seg =~ /Womens E-Mail/)
    {
        $seg = 1;
    }
    $seg = 1 << ($seg-1);
    $seg = sprintf("%b,%b,%b",($seg & 1)>>0,($seg & 2)>>1,($seg & 4)>>2);

    print $output "$rec,$hist_seg,$hist,$mens,$womens,$zip,$newb,$chan,$seg,$visit,$conv,$spend\n";
}

close($fh);
close($output);
